package com.coder.bike.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coder.bike.entity.BikeInfo;
import com.coder.bike.entity.Maintain;
import com.coder.bike.service.IBikeInfoService;
import com.coder.bike.service.IMaintainService;
import com.coder.bike.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/bike/maintain")
public class MaintainController {
    @Resource
    private IMaintainService maintainService;

    @Resource
    private IBikeInfoService bikeInfoService;

    @PostMapping("{start}/{size}")
    public Result search(@PathVariable int start,
                         @PathVariable int size,
                         @RequestBody Maintain maintain) {
        Page<Maintain> page = new Page<>(start, size);
        return Result.success(maintainService.searchByPage(page, maintain));
    }

    @PostMapping
    public Result save(@RequestBody Maintain maintain) {
        // 设置单车信息
        BikeInfo bikeInfo = bikeInfoService.getByBikeId(maintain.getBikeId());
        if (bikeInfo != null) {
            // 更新单车最后维护时间
            bikeInfo.setLastMaintain(maintain.getEndTime());
            bikeInfoService.updateById(bikeInfo);
        }
        return maintainService.save(maintain) ?
                Result.success() : Result.fail();
    }

    @PutMapping
    public Result update(@RequestBody Maintain maintain) {
        return maintainService.updateById(maintain) ?
                Result.success() : Result.fail();
    }

    @DeleteMapping("{ids}")
    public Result delete(@PathVariable String ids) {
        return maintainService.delete(ids) ?
                Result.success() : Result.fail();
    }

    @GetMapping("toBeMaintained")
    public Result toBeMaintained() {
        return Result.success(bikeInfoService.toBeMaintained());
    }
}